package com.jack.tang.juc.demos;



import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class communicate3 {
    public static void main(String[] args) {
        Data2 data = new Data2();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data.plus();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "A").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data.minor();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "B").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data.plus();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "C").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data.minor();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "D").start();
    }
}

class Data2 {
    private int number = 0;
    //创建Lock锁
    private Lock lock = new ReentrantLock();
    //获得condition
    Condition condition = lock.newCondition();

    //如果number=0,则number+1
    public void plus() throws InterruptedException {
        lock.lock();//加锁
        try {
            while (number != 0)
                condition.await();//等待
            number++;
            System.out.println(Thread.currentThread().getName() + "=>" + number);
            condition.signalAll();//唤醒其他线程
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();//解锁
        }
    }

    //如果number!=0,则number-1
    public void minor() throws InterruptedException {
        lock.lock();
        try {
            while (number == 0)
                condition.await();
            number--;
            System.out.println(Thread.currentThread().getName() + "=>" + number);
            condition.signalAll();//唤醒其他线程
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
